import uuid
from django.http import JsonResponse
from django import forms
from datetime import datetime

from BloodSpiderModel.DjangoResponseTool.response_dict import response_dict, get_first_error, get_page
from BloodSpiderAPI import models
from BloodSpiderAPI.apis.product import utils as product_utils
from django.db.models import Q


# 商品表单验证
class ProductForm(forms.ModelForm):
    class Meta:
        model = models.Product
        fields = ['name', 'description', 'points', 'stock', 'cover_url', 'delivery_method']
    
    # 自定义验证方法
    def clean_points(self):
        points = self.cleaned_data.get('points')
        if points < 0:  # 确保积分非负
            raise forms.ValidationError("积分不能为负数")
        return points
        
    def clean_stock(self):
        stock = self.cleaned_data.get('stock')
        if stock < 0:  # 确保库存非负
            raise forms.ValidationError("库存不能为负数")
        return stock


# 创建商品
def create_product(request):
    """
    创建新商品API
    支持POST请求
    参数: name(商品名称), description(商品描述), points(商品积分), stock(商品库存), cover_url(商品封面图URL), delivery_method(发货方式描述)
    返回: 创建成功的商品信息或错误信息
    """
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    # 为商品生成唯一ID
    data = request.POST.dict()
    data['pid'] = str(uuid.uuid4())  # 生成UUID作为商品ID
    
    form = ProductForm(data)
    if not form.is_valid():
        return response_dict(data=get_first_error(form), code=1, message="参数错误")
    
    try:
        product = form.save()
        response = product_utils.utils_model_to_dict(product)
        return response_dict(message="商品创建成功", code=0, data=response)
    except Exception as e:
        return response_dict(message=f"创建失败: {str(e)}", code=1)


# 获取单个商品
def get_product(request):
    """
    获取单个商品API
    支持POST请求
    参数: pid(商品ID)
    返回: 商品信息或错误信息
    """
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    pid = request.POST.get('pid')
    if not pid:
        return response_dict(message="商品ID不能为空", code=1)
    
    try:
        product = models.Product.objects.get(pid=pid)
        response = product_utils.utils_model_to_dict(product)
        return response_dict(message="商品信息获取成功", code=0, data=response)
    except models.Product.DoesNotExist:
        return response_dict(message="商品不存在", code=1)
    except Exception as e:
        return response_dict(message=f"获取失败: {str(e)}", code=1)


# 更新商品
def update_product(request):
    """
    更新商品API
    支持POST请求
    参数: pid(商品ID), 其他可选字段(name, description, points, stock, cover_url, delivery_method)
    返回: 更新后的商品信息或错误信息
    """
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    pid = request.POST.get('pid')
    if not pid:
        return response_dict(message="商品ID不能为空", code=1)
    
    try:
        product = models.Product.objects.get(pid=pid)
        
        # 仅更新传入的字段
        data = request.POST.dict()
        # 移除pid，避免更新主键
        data.pop('pid', None)
        
        # 验证更新的字段
        for key, value in data.items():
            if hasattr(product, key):
                # 特殊处理积分和库存字段
                if key == 'points' or key == 'stock':
                    try:
                        value = int(value)
                        if value < 0:
                            return response_dict(message=f"{key}不能为负数", code=1)
                        setattr(product, key, value)
                    except ValueError:
                        return response_dict(message=f"{key}必须是整数", code=1)
                else:
                    setattr(product, key, value)
        
        product.save()
        response = product_utils.utils_model_to_dict(product)
        return response_dict(message="商品更新成功", code=0, data=response)
    except models.Product.DoesNotExist:
        return response_dict(message="商品不存在", code=1)
    except Exception as e:
        return response_dict(message=f"更新失败: {str(e)}", code=1)


# 删除商品
def delete_product(request):
    """
    删除商品API
    支持POST请求
    参数: pid(商品ID)
    返回: 删除结果信息
    """
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    pid = request.POST.get('pid')
    if not pid:
        return response_dict(message="商品ID不能为空", code=1)
    
    try:
        product = models.Product.objects.get(pid=pid)
        product.delete()
        return response_dict(message="商品删除成功", code=0)
    except models.Product.DoesNotExist:
        return response_dict(message="商品不存在", code=1)
    except Exception as e:
        return response_dict(message=f"删除失败: {str(e)}", code=1)


# 获取全部商品列表
def get_product_list(request):
    """
    获取全部商品列表API
    支持POST请求
    参数: keyword(名称模糊查询), page(页码), page_size(每页数量)
    返回: 商品列表或错误信息
    """
    if request.method != 'POST':
        return response_dict(message="请使用POST请求", code=1)
    
    keyword = request.POST.get('keyword', '')
    page = request.POST.get('page', 1)
    page_size = request.POST.get('page_size', 10)
    
    # 构建查询条件
    query = Q()
    if keyword:
        query &= Q(name__icontains=keyword)
    
    products = models.Product.objects.filter(query).order_by('-create_time')
    
    # 分页处理
    page_data = get_page(products, page_size, page)
    
    # 转换数据格式
    product_list = []
    for product in page_data['page']['object_list']:
        product_list.append(product_utils.utils_model_to_dict(product))
    
    page_data['page']['object_list'] = product_list
    
    return response_dict(message="商品列表获取成功", code=0, data=page_data)